<script setup lang="ts">
import {onMounted, ref} from "vue";
import {getCategoryAPI, addGoodsAPI} from "@/axios/api";
import {ElMessage} from "element-plus";

interface use {
  cid: number | null
  name: string | null
  per: string | null
  remark: string | null
}

const labelText = {
  category: "分类名称",
  commodityName: "商品名称",
  unit: "单位",
  remark: "备注"
}
const categoryNameList = ref([])
const goodsForm = ref<use>({
  cid: Number() || null,
  name: "",
  per: "",
  remark: ""
})
const optionList=ref(["斤","千克","升"])
function getCategory() {
  getCategoryAPI({
    pageNum: null,
    pageSize: 10,
    sort: 1
  }).then(data => {
    categoryNameList.value = data.data.data
  })
}

function empty() {
  for (const key in goodsForm.value) {
    goodsForm.value[key] = null
  }
}

function addGoods() {
  if (goodsForm.value.cid == null) {
    ElMessage.error("分类不能为空")
    return
  }
  if (goodsForm.value.name == null ||
      goodsForm.value.name == "") {
    ElMessage.error("商品名称不能为空")
    return
  }
  if (goodsForm.value.per == null ||
      goodsForm.value.per === "") {
    ElMessage.error("单位不能为空")
    return;
  }
  addGoodsAPI(goodsForm.value).then(data => {
    ElMessage.success(data.data.data)
    empty()
  })
  empty()
}

onMounted(() => {
  getCategory()
})
</script>
<template>
  <el-form
      :model="goodsForm"
      label-width="auto"
      style="max-width: 600px"
  >

    <el-form-item
        :label="`${labelText.category}:`"
    >
      <el-select
          v-model="goodsForm.cid"
          placeholder="请选择分类"
          filterable
      >
        <template #empty>暂无数据</template>
        <el-option
            v-for="item in categoryNameList"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item
        :label="`${labelText.commodityName}:`"
    >
      <el-input
          type="text"
          placeholder="请输入商品名称"
          v-model="goodsForm.name"
          maxlength="10"
          show-word-limit
      />
    </el-form-item>

    <el-form-item
        :label="`${labelText.unit}:`"
    >
      <el-select
          v-model="goodsForm.per"
          placeholder="请输入单位，如：斤，千克"
          filterable
          allow-create
      >
        <el-option
            v-for="item in optionList"
            :label="item"
            :value="item"
        />
      </el-select>
    </el-form-item>

    <el-form-item
        :label="`${labelText.remark}:`"
    >
      <el-input
          v-model="goodsForm.remark"
          type="textarea"
          placeholder="请输入备注信息"
          show-word-limit
          maxlength="250"
      />
    </el-form-item>

    <el-form-item
        label=" "
    >
      <el-button
          @click="addGoods"
          type="primary"
      >添加
      </el-button>
      <el-button
          @click="empty"
      >取消
      </el-button>
    </el-form-item>
  </el-form>
</template>